package commons.base.http.example;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class HttpTest3 {

	public static void main(String[] args)throws Exception {
		t1();

	}
	
	public static void t1()throws Exception{
		ExecutorService executorService = Executors.newCachedThreadPool();
		
		HttpTask httpTask = new HttpTask();
		Future<String> future = executorService.submit(httpTask);
		try {
			String response = future.get(3, TimeUnit.SECONDS);
			System.err.println(response);
		} catch (TimeoutException e) {
			e.printStackTrace();
			httpTask.shutdown();
		}
		
		executorService.shutdownNow();
	}

}

class HttpTask implements Callable<String>{
	private HttpURLConnection conn;
	
	@Override
	public String call() {
		String responseText = null;
		try{
			
			URL url = new URL("http://www.baidu.com");
			conn = (HttpURLConnection)url.openConnection();
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod("GET");
			conn.connect();
			
			responseText = readResponse(conn, "UTF-8");
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(conn != null)
				conn.disconnect();
		}
		return responseText;
	}
	
	public void shutdown(){
		if(conn != null)
			conn.disconnect();
	}
	
	private String readResponse(HttpURLConnection conn, String charset) throws IOException{
		InputStream is = conn.getErrorStream();
		if(is == null){
			is = conn.getInputStream();
		}
		
		return readInputStream(is, charset);
	}
	private String readInputStream(InputStream is, String charset)throws IOException{
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		int data = 0;
		while((data = is.read()) != -1){
			baos.write(data);
		}
		
		return new String(baos.toByteArray(), charset);
	}
}